//
//  HMOAuthViewController.swift
//  weibo10
//
//  Created by mac on 15/10/19.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class HMOAuthViewController: UIViewController {
    private lazy var webView = UIWebView()
    // MARK -注册 “关闭” 点击事件
    @objc private func closeClick(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK -自动填充
    @objc func autoLogin(){
        let js = "document.getElementById('userId').value = 'ntt0302@sina.cn';" +
        "document.getElementById('passwd').value = 'tiantian0302';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    // MARK -设置界面
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "登录新浪微博界面"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: Selector("closeClick"))
        // 自动填充：便于测试
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: Selector("autoLogin"))
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }
}
// MARK: - UIWebViewDelegate
extension HMOAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            closeClick()
            return false
        }
        print(query)
        let code = query.substringFromIndex("code=".endIndex)
        print("code= \(code)")
        HMUserAcountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccess) -> () in
            if !isSuccess {
                print("出错了")
                SVProgressHUD.showErrorWithStatus("登录失败")
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//                    self.closeClick()
//                })
                delay(0.8, callBack: { () -> () in
                    self.closeClick()
                })
                
                
            }else{
                print("成功呢")
                self.dismissViewControllerAnimated(false){ () -> Void in
                     NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "OAuth")
                }
               
            }
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
